/*
 * CAppStateCreateGame.cpp
 *
 *  Created on: 24/12/2012
 *
 */

#include "CAppStateCreateGame.h"
#include "CAppStateManager.h"
#include "CSurface.h"
#include <iostream>
#include <string>
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_net.h>
#include "SurfaceWrapper.h"
#include "util.h"
#include <sstream>


using namespace std;

extern GAME_STATE gameState;

CAppStateCreateGame CAppStateCreateGame::instance;


CAppStateCreateGame::CAppStateCreateGame(){
	surface = NULL;
	font = NULL;
	bar = NULL;
	nickWrapper = "";
	userIp = NULL;
	color = {0,37,83};
	userNick = NULL;
}

/**
 * Gerencia os eventos do teclado
 */
void CAppStateCreateGame::onKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {

	if (sym == SDLK_BACKSPACE) {
		if (!nickWrapper.empty())
			nickWrapper.erase(nickWrapper.length() - 1);
	} else if (sym == SDLK_RETURN) {
		if (!nickWrapper.empty()) {
			// Do stuff with the text
		}
	} else {
		if (nickWrapper.length() < MAX_NICK_LENGTH) {
			if (unicode == ' ' || unicode >= 'a' && unicode <= 'z'
					|| unicode >= 'A' && unicode <= 'Z'
					|| unicode >= '0' && unicode <= '9')
				nickWrapper += (char) unicode;
		}
	}
}

/**
 * Carrega as telas
 */
void CAppStateCreateGame::onActivate(){
	gameState = SERVIDOR;
	if((surface = CSurface::onLoad(".//data/imgs/criar-game.png")) == NULL){
		return;
	}

	if((bar = CSurface::onLoad(".//data/imgs/barra_text.png")) == NULL){
			return;
	}
	font = TTF_OpenFont(".//data/fonts/tahoma.TTF", 18);

	SDL_EnableUNICODE(SDL_ENABLE);

}

void CAppStateCreateGame::onLButtonDown(int mX, int mY){

	if (mX >= 360 && mX <= 530 && mY >= 490 && mY <= 530 ){
		//Enterou no Criar!
		CAppStateManager::setActiveAppState(APPSTATE_STAGE, new DataLoader(nickWrapper, NULL));
	} else if (mX >= 570 && mX <= 740 && mY >= 490 && mY <= 530 ){
		//entrou no cancelar
		CAppStateManager::setActiveAppState(APPSTATE_MENU, NULL);

	}
}



void CAppStateCreateGame::onDeactivate(){
	SDL_FreeSurface(surface);
	surface = NULL;
	SDL_FreeSurface(bar);
	bar = NULL;
	nickWrapper = "";
	SDL_FreeSurface(userIp);
	userIp = NULL;
	SDL_FreeSurface(userNick);
	userNick = NULL;
	SDL_FreeSurface(userIp);
	userIp = NULL;
	font = NULL;
	SDL_EnableUNICODE(SDL_DISABLE);

}

void CAppStateCreateGame::onLoop(){
	SDL_FreeSurface(userNick);
	userNick = NULL;
	userNick = TTF_RenderText_Blended(font, nickWrapper.c_str(), color);
}

void CAppStateCreateGame::onRender(SDL_Surface* surfDisplay){
	int nickAddition = 0;

	if(surface){
		CSurface::onDraw(surfDisplay, surface,0,0);
	}

	if(userNick != NULL){
		CSurface::onDraw(surfDisplay,userNick,370,340);
		nickAddition = userNick->w;
	}
	CSurface::onDraw(surfDisplay,bar,370 + nickAddition, 340);
}


CAppStateCreateGame* CAppStateCreateGame::getInstance(){
	return &instance;
}



